package com.boruan.qq.zxgylibrary.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseOneActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.service.presenter.FirstPagePresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 崔琦 on 2019/9/7.
 * des: 位置搜索页
 */

public class SelectAddressActivity extends BaseOneActivity implements PoiSearch.OnPoiSearchListener {

    @BindView(R2.id.edt_search_content)
    EditText edtSearchContent;
    @BindView(R2.id.tv_current_position)
    TextView tvCurrentPosition;
    @BindView(R2.id.dialog_search_recycle)
    RecyclerView dialogSearchRecycle;
    @BindView(R2.id.tv_current_city)
    TextView tvCurrentCity;
    @BindView(R2.id.ll_current_position)
    LinearLayout llCurrentPosition;

    private SearchAdapter searchAdapter;
    private String deepType = "";// poi搜索类型
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private List<PoiItem> poiItems;// poi数据

    //当前定位的城市名
    private String mCity;
    private FirstPagePresenter firstPagePresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.drug_activity_position_search;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mCity = ConstantInfo.mCity;
        tvCurrentCity.setText(ConstantInfo.mCity);
        tvCurrentPosition.setText(ConstantInfo.mDistrict);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        dialogSearchRecycle.setLayoutManager(manager);
        searchAdapter = new SearchAdapter();
        dialogSearchRecycle.setAdapter(searchAdapter);
        poiItems = new ArrayList<>();
        /**
         * 输入监听
         * */
        edtSearchContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                textChangeSearch(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        firstPagePresenter = new FirstPagePresenter(this);
        firstPagePresenter.onCreate();
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    Log.i("Items", poiItems.size() + "");
                    List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();
                    if (poiItems != null && poiItems.size() > 0) {
                        searchAdapter.setData(poiItems);
                        llCurrentPosition.setVisibility(View.GONE);
                    } else {
                        llCurrentPosition.setVisibility(View.VISIBLE);
                        Toast.makeText(this, "没有查询到结果！", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Log.i("TAG", "无结果");
                }
            }
        } else {
            Log.i("TAG", "无结果");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    private void textChangeSearch(CharSequence charSequence) {
        String content = charSequence.toString().trim();//获取自动提示输入框的内容
        int currentPage = 0;
        query = new PoiSearch.Query(content, deepType, mCity);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();// 异步搜索
    }

    @OnClick({R2.id.back, R2.id.tv_again_location,R2.id.tv_current_position})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.back) {
            finish();

        } else if (i == R.id.tv_again_location) {
            firstPagePresenter.startLocation(tvCurrentPosition, 1);

        } else if (i == R.id.tv_current_position) {
            Intent intent = new Intent();
            intent.putExtra("address", ConstantInfo.mDistrict);
            intent.putExtra("lat", ConstantInfo.lat);
            intent.putExtra("lon", ConstantInfo.lng);
            setResult(22, intent);
            finish();

        }
    }

    /**
     * poi适配器
     */
    private class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
        private List<PoiItem> mData;

        public void setData(List<PoiItem> mData) {
            this.mData = mData;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public SearchViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View view = inflater.inflate(R.layout.drug_item_search, parent, false);
            return new SearchViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
            holder.tvCityName.setText(mData.get(position).getTitle());
            holder.tvCityContent.setText(mData.get(position).getSnippet());
            holder.tvLocation.setText(fromMeter2KM(gps2m(mData.get(position).getLatLonPoint().getLatitude(), mData.get(position).getLatLonPoint().getLongitude(), ConstantInfo.lat, ConstantInfo.lng)));
            holder.llSearchMain.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    hideKeyboard();
                    Intent intent = new Intent();
                    intent.putExtra("address", mData.get(position).getTitle());
                    intent.putExtra("lat", mData.get(position).getLatLonPoint().getLatitude());
                    Log.i("test", mData.get(position).getLatLonPoint().getLatitude() + "");
                    intent.putExtra("lon", mData.get(position).getLatLonPoint().getLongitude());
                    intent.putExtra("province",mData.get(position).getProvinceName());
                    intent.putExtra("city",mData.get(position).getCityName());
                    intent.putExtra("area",mData.get(position).getAdName());
                    setResult(22, intent);
                    finish();
                }
            });
        }

        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.size();
        }

        public class SearchViewHolder extends RecyclerView.ViewHolder {
            LinearLayout llSearchMain;
            TextView tvCityName;
            TextView tvCityContent;
            TextView tvLocation;

            public SearchViewHolder(View itemView) {
                super(itemView);
                llSearchMain = (LinearLayout) itemView.findViewById(R.id.ll_search_main);
                tvCityName = (TextView) itemView.findViewById(R.id.tv_city_name);
                tvCityContent = (TextView) itemView.findViewById(R.id.tv_city_content);
                tvLocation = (TextView) itemView.findViewById(R.id.tv_location);
            }
        }
    }

    public void hideKeyboard() {
        View view = SelectAddressActivity.this.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 地球半径
     */
    private int EARTH_RADIUS = 6371000;

    private double gps2m(double lat_a, double lng_a, double lat_b, double lng_b) {
        double radLat1 = (lat_a * Math.PI / 180.0);
        double radLat2 = (lat_b * Math.PI / 180.0);
        double a = radLat1 - radLat2;
        double b = (lng_a - lng_b) * Math.PI / 180.0;
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    /**
     * 将m装换成km
     */
    public static String fromMeter2KM(double meters) {
        meters = Math.round(meters / 100d) / 10d;
        String s = String.valueOf(meters);
        if (s.equals("0.0")) {
            s = "0";
        }
        s += "km";
        return s;
    }
}
